package com.ptadmin.report.executor.processor;

import java.io.File;
import java.sql.Connection;
import java.sql.Statement;
import java.util.Iterator;

import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;

import com.google.gson.JsonParser;
import com.ptadmin.report.postgresql.PostgreSqlHelper;

public class BrowseTreeReportPGProcessor {

	SAXReader reader = new SAXReader();
	JsonParser parser = new JsonParser();
	private String tableName = "public.table1";
	
	public void process(ProcessReportsParameter param) {
		try {
			String reportFilePath = param.getReportFilePath();
			
			Document document = reader.read(new File(reportFilePath));
			Element rootElement = document.getRootElement();

			Iterator it = rootElement.elementIterator();
			int count = 1;
			String sql_value = "";
			while (it.hasNext()) {
				Element element = (Element) it.next();
				String xml = element.asXML();

				String nodeId = element.elementText("browseNodeId");
				String json = org.json.XML.toJSONObject(xml).toString();

				Connection c = null;
				Statement stmt = null;

				sql_value += "('" + nodeId + "', '" + json.replace('\'', '`') + "' ),";
				if (count % 1000 == 0) {
					sql_value = sql_value.substring(0, sql_value.length() - 1) + ";";
					String sql = "INSERT INTO " + tableName + " (\"BrowseNodeID\",\"Content\") " + "VALUES "
							+ sql_value;
					sql_value = "";
					PostgreSqlHelper sqlHelper = new PostgreSqlHelper();
					sqlHelper.executeSqlString(sql);
					System.out.println(String.format("Opened database successfully, finished %s records", count));
				}

				count++;
			}
			sql_value = sql_value.substring(0, sql_value.length() - 1) + ";";
			String sql = "INSERT INTO public.table1 (\"BrowseNodeID\",\"Content\") " + "VALUES " + sql_value;
			sql_value = "";
			PostgreSqlHelper sqlHelper = new PostgreSqlHelper();
			sqlHelper.executeSqlString(sql);

			System.out.println(String.format("Opened database successfully, finished %s records", count));
			System.out.println("total records: " + count);

		} catch (DocumentException e) {
			e.printStackTrace();
		} catch (Exception e) {
			e.printStackTrace();
			System.err.println(e.getClass().getName() + ": " + e.getMessage());
			System.exit(0);
		}
	}
	
	public static void main(String... args) {
		ProcessReportsParameter param = new ProcessReportsParameter();
		param.setMerchantId("test");
		param.setReportCategory("browseTreeNode");
		param.setReportFilePath("report.xml");
		param.setReportName("browseTreeNode");
		
		BrowseTreeReportPGProcessor processor = new BrowseTreeReportPGProcessor();
		processor.process(param);
	}
}
